Modifying graph structure using a set-based adjacency list.

  • Using Python's set for neighbor lists makes adding and removing edges highly efficient, typically an O(1) operation on average.
  • To maintain the graph's integrity, it's crucial to perform the operation in both directions. Forgetting `adj[v].add(u)` after `adj[u].add(v)` would break the symmetry of an undirected graph.
  • The `.discard()` method is used for removal because it won't raise an error if the edge doesn't exist, making the function more robust.
Python: Undirected Edge Modification
def add_edge(adj,u,v):
    adj[u].add(v); adj[v].add(u)
def remove_edge(adj,u,v):
    adj[u].discard(v); adj[v].discard(u)